//
//  AddressManager.swift
//  JiaoZiTaxi
//
//  Created by hc-101 on 2024/7/6.
//

import SwiftUI
import MapKit


//struct SegmentModel  : Hashable {
//    var title: String
//    var request: String
//    // 自动生成的 Hashable 实现
//        func hash(into hasher: inout Hasher) {
//            hasher.combine(title)
//            hasher.combine(request)
//        }
//        
//        static func == (lhs: SegmentModel, rhs: SegmentModel) -> Bool {
//            return lhs.title == rhs.title && lhs.request == rhs.request
//        }
//}

struct PrivateAddressView: View {
    
    
    var vm = ViewModel.shared
    
    @Environment(\.dismiss) var dismiss
       
    
    @State var region: MKCoordinateRegion
    
    @State var selectCoordinate: CLLocationCoordinate2D
    
    @State var selectType: String
    
    @ObservedObject var carOrder = CarOrder.shared
    @StateObject private var addressManager = MyAddressNetManager()
    
    @State private var keyword: String = ""     // 搜索地址名称
    @State var addAddressAction: Bool = false    // 是否添加位置
    @State var isPublic: Bool = false           // 是公开地址
    @State private var addressName: String = ""
    @State var aId: String = ""
    @State var showAlert = false        // 是否展示弹框
    @State var showSheet = false
    
    var segmentTypes: [SegmentModel] = [SegmentModel(title: "公共定位".localized(),request: "public"),
                                        SegmentModel(title: "私有定位".localized(),request: "private")]
    @State private var selected : SegmentModel = SegmentModel(title: "私有定位".localized(),request: "private")
    
 
    
    var action : ()->Void
    
    
    
    var body: some View {
        GeometryReader(content: { geometry in
            
            NavigationView {
                VStack {
                    
                    // MARK: 中间三个tab按钮
//                    createHoriSegment()
//                        .padding(.horizontal,30)
//                        .padding(.vertical,15)
                    // MARK: 下边的三个分页
                    ZStack {
                        // MARK: 2.私有定位位置页面
                        if self.selected.request == "private" {
                            ZStack {
                                VStack (spacing:0) {
                                    // 列表
                                    List{
                                        
//                                        if addressManager.addressLocalList.count > 0 {
//                                            
//                                            HStack{
//                                                Text("历史记录").font(.system(size: 18,weight: .bold)).foregroundColor(.black)
//                                                Spacer()
//                                                Button {
//                                                    addressManager.clearLocalAddressList()
//                                                } label: {
//                                                    Text("清空").font(.system(size: 12)).foregroundColor(.gray)
//                                                }.frame(width:60, height: 30)
//                                            }
//                                            .frame(maxWidth: .infinity, alignment: .leading).listRowSeparator(.hidden)
//                                            
//                                            ForEach(addressManager.addressLocalList, id: \.self) { address in
//                                                Button {
//                                                    let lat = address.latitude
//                                                    let lon = address.longitude
//                                                    let pos = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
//                                                    if self.selectType == "start" {
//                                                        ViewModel.shared.startLocation = pos
//                                                        carOrder.startPos = pos
//                                                        MapConfig.shared.startOrEndChanged = true
//                                                        //                                                        carOrder.startLabel = "\("出发地：\(address.name!)".localized())"
//                                                    }else{
//                                                        ViewModel.shared.endLocation = pos
//                                                        carOrder.endPos = pos
//                                                        MapConfig.shared.startOrEndChanged = true
//                                                        carOrder.endLabel = "\(address.name ?? "")"
//                                                    }
//                                                    self.action()
//                                                    dismiss()
//                                                } label: {
//                                                    createPublicCell(address: address)
//                                                    
//                                                }
//                                                //                                        if address == $addressManager.addressLocalList.last {
//                                                //                                            .listRowSeparator(.hidden)
//                                                //                                        }
//                                            }
//                                            // 自定义间距
//                                            Rectangle()
//                                                .fill(Color.gray.opacity(0.1))
//                                                .frame(height: 20).listRowInsets(EdgeInsets()).listRowSeparator(.hidden)
//                                            
//                                        }
                                        
                                        
                                        Section{
                                            
                                            ForEach(addressManager.addressPrivateList, id: \.self) { address in
                                                Button {
                                                    let lat = address.latitude
                                                    let lon = address.longitude
                                                    let pos = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
                                                    if self.selectType == "start" {
                                                        ViewModel.shared.startLocation = pos
                                                        carOrder.startPos = pos
                                                        MapConfig.shared.startOrEndChanged = true
                                                        //                                                        carOrder.startLabel = "\("出发地：\(address.name!)".localized())"
                                                    }else{
                                                        ViewModel.shared.endLocation = pos
                                                        carOrder.endPos = pos
                                                        MapConfig.shared.startOrEndChanged = true
                                                        carOrder.endLabel = "\(address.name ?? "")"
                                                    }
                                                    self.action()
                                                    dismiss()
                                                    // 保存地址
                                                    if let addressModel = address as? AddressModel {
                                                        addressManager.setLocalAddress(address: address)
                                                    }
                                                    
                                                } label: {
                                                    createPrivateCell(address: address)
                                                }
                                            }
                                        } header:{
                                            
                                        }
                                    }.listStyle(PlainListStyle())
                                        .padding(0)
                                        .background(.clear)
                                    Button(action: {
                                        self.addAddressAction = true
                                    }, label: {
                                        HStack {
                                            Image(systemName: "plus")
                                                .foregroundColor(.white)
                                            Text("添加位置")
                                        }
                                        .frame(width: 320, height: 48)
                                        .background(Color.themeColor())
                                        .foregroundColor(.white)
                                        .cornerRadius(6)
                                    })
                                }
                                .padding()
                                .frame(width: geometry.size.width)
                                .background(Color.backgroundColor())
                                //                            .overlay(
                                //                                RoundedRectangle(cornerRadius: 10, style: .circular).stroke(Color(uiColor: .tertiaryLabel), lineWidth: 1)
                                //                            )
                                
                                // FIX: 无数据占位图
                                if addressManager.addressPrivateList.count <= 0  && addressManager.addressLocalList.count <= 0{
                                    VStack {
                                        Spacer()
                                        Image("no_data_holder")
                                            .resizable()
                                            .frame(width: 180, height: 165)
                                        Text("没有位置")
                                            .font(.system(size: 14))
                                            .foregroundColor(Color(hex: "#999999"))
                                        Spacer()
                                        Spacer()
                                    }
                                    .padding(.horizontal, 100)
                                }
                            }.onAppear {
                                addressManager.loadAddressList(index: self.selected.request, keyword: keyword)
                                addressManager.loadLocalAddressList()
                            }
                            
                            // add address blank
                            if self.addAddressAction {
                                Color.black.opacity(0.5)
                                //                            VStack 
                                createAddAddressView()
                            }
                            
                        }
                        
                        // MARK: 3.选择位置页面
                        if self.selected.request == "public" {
                            VStack {
                                HStack {
                                    Image(systemName: "magnifyingglass")
                                        .foregroundColor(Color(hex: "#999999"))
                                    TextField("您要去哪儿", text: $keyword).padding()
                                    Button(action: {
                                        addressManager.loadAddressList(index: self.selected.request, keyword: keyword)
                                        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                                    }, label: {
                                        Text("搜索")
                                            .font(.system(size: 14))
                                            .foregroundColor(.white)
                                    })
                                    .frame(width: 60, height: 30)
                                    .background(Color.themeColor())
                                    .cornerRadius(4)
                                    
                                }
                                .padding(.horizontal , 12)
                                .background(.white)
                                .cornerRadius(6)
                                
                                
                                
                                
                                // 列表
                                List {
                                    if addressManager.addressLocalList.count > 0 {
                                        
                                        HStack{
                                            Text("历史记录").font(.system(size: 18,weight: .bold)).foregroundColor(.black)
                                            Spacer()
                                            Button {
                                                addressManager.clearLocalAddressList()
                                            } label: {
                                                Text("清空").font(.system(size: 12)).foregroundColor(.gray)
                                            }.frame(width:60, height: 30)
                                        }
                                        .frame(maxWidth: .infinity, alignment: .leading).listRowSeparator(.hidden).background(.white)
                                        
                                        ForEach(addressManager.addressLocalList, id: \.self) { address in
                                            Button {
                                                let lat = address.latitude
                                                let lon = address.longitude
                                                let pos = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
                                                if self.selectType == "start" {
                                                    ViewModel.shared.startLocation = pos
                                                    carOrder.startPos = pos
                                                    MapConfig.shared.startOrEndChanged = true
                                                    //                                                        carOrder.startLabel = "\("出发地：\(address.name!)".localized())"
                                                }else{
                                                    ViewModel.shared.endLocation = pos
                                                    carOrder.endPos = pos
                                                    MapConfig.shared.startOrEndChanged = true
                                                    carOrder.endLabel = "\(address.name ?? "")"
                                                }
                                                self.action()
                                                dismiss()
                                            } label: {
                                                createPublicCell(address: address).background(.white)
                                                
                                            }.background(.white)
                                            //                                        if address == $addressManager.addressLocalList.last {
                                            //                                            .listRowSeparator(.hidden)
                                            //                                        }
                                        }
                                        
                                        
                                    }
                                    
                                    if addressManager.addressPublicList.count > 0 && addressManager.addressLocalList.count > 0 {
                                        
                                        Rectangle()
                                            .fill(Color.gray.opacity(0.1))
                                            .frame(height: 20).listRowInsets(EdgeInsets()).listRowSeparator(.hidden)
                                    }
                                    
                                    
                                    ForEach(addressManager.addressPublicList, id: \.self) { address in
                                        Button {
                                            let lat = address.latitude
                                            let lon = address.longitude
                                            let pos = CLLocationCoordinate2D(latitude: lat!, longitude: lon!)
                                            if self.selectType == "start" {
                                                ViewModel.shared.startLocation = pos
                                                carOrder.startPos = pos
                                                MapConfig.shared.startOrEndChanged = true
                                                //                                            carOrder.startLabel = "\("出发地：\(address.name!)".localized())"
                                                //                                                carOrder.startLabel = "\(address.name!) \(String(format: "%.6f", pos.latitude)),\(String(format: "%.6f", pos.longitude))"
                                            }else{
                                                ViewModel.shared.endLocation = pos
                                                carOrder.endPos = pos
                                                MapConfig.shared.startOrEndChanged = true
                                                carOrder.endLabel = "\(address.name!)"
                                                //                                                carOrder.endLabel = "\(address.name!) \(String(format: "%.6f", pos.latitude)),\(String(format: "%.6f", pos.longitude))"
                                            }
                                            self.action()
                                            dismiss()
                                            addressManager.setLocalAddress(address: address)
                                            
                                        } label: {
                                            createPublicCell(address: address)
                                        }
                                    }
                                }
                                .listStyle(PlainListStyle())
                                .padding(.vertical,15)
                                .background(.clear)
                                
                            }
                            .padding(10)
                            .frame(width: geometry.size.width)
                            .background(Color.backgroundColor())
                            .onAppear {
                                addressManager.loadLocalAddressList()
                                addressManager.loadAddressList(index: self.selected.request, keyword: keyword)
                            }
                        }
                    }
                }
            }.navigationBarBackButtonHidden(true)
                .navigationBarItems(leading: backButton)  // 隐藏默认返回按钮
                        .navigationTitle("我的地址")
        })
    }
    
    var backButton: some View {
        Button(action: {
            dismiss()
        }) {
            HStack {
                Image(systemName: "chevron.backward").foregroundColor(Color(hex: 0x333333))
            }
        }
    }
    func addAddress(text: String) {
        if text.isEmpty {
            return
        }
        saveAddressAction(aId: self.aId, name: self.addressName, lat: "\(self.selectCoordinate.latitude)", lon: "\(self.selectCoordinate.longitude)", type: self.isPublic ? "public" : "private") { result in
            self.addAddressAction = false
            if !self.isPublic {
                addressManager.loadAddressList(index: self.selected.request, keyword: "")
            }
        }
        
    }
    
    func deletAddress() {
        let openId = ViewModel.shared.passenger.openId
        Api.deleteAddress(aId: self.aId, openId: openId) { r in
            addressManager.loadAddressList(index: "private", keyword: "")
        }
    }
    
}

private extension PrivateAddressView {
    //
    func createHoriSegment()->some View{
        HStack {
//            RadioButton(item: self.segmentTypes[0], selectedOption: $selected) {
//                self.selected = self.segmentTypes[0]
//            }
            Spacer()
//            Image("more-square")
//            Spacer()
            
            RadioButton(item: self.segmentTypes[1], selectedOption: $selected) {
                self.selected = self.segmentTypes[1]
            }
            Spacer()
//            Image("more-square")
//            Spacer()
//            HStack {
//                 Image("地图选点_设置").resizable().frame(width:16, height:16)
//                 Text("地图选点").font(.system(size: 13))
//             }
//             .padding(.vertical, 8)
//             .onTapGesture {
//             }
        }
    }
    
    func createAddAddressView()->some View{
        VStack {
            Spacer()
            VStack {
                VStack (spacing: 10) {
                    VStack {
                        TextField("您要去哪儿", text: $addressName).padding()
                    }
                    .frame(height: 46)
                    .padding(.horizontal, 10)
                    .background(Color(hex: "#EBEDF5"))
                    
                    HStack {
                        Text("\(self.selectCoordinate.longitude)")
                        Spacer()
                    }
                    .frame(height: 46)
                    .padding(.horizontal, 20)
                    .background(Color(hex: "#EBEDF5"))
                    
                    HStack {
                        Text("\(self.selectCoordinate.latitude)")
                        Spacer()
                    }
                    .frame(height: 46)
                    .padding(.horizontal, 20)
                    .background(Color(hex: "#EBEDF5"))
                    
                    HStack {
                        Button {
                            self.isPublic = false
                        } label: {
                            HStack {
                                Image(systemName: self.isPublic ? "circle" : "checkmark.circle.fill")
                                    .foregroundColor(self.isPublic ? Color.black  : Color.themeColor())
                                Text("私有")
                                    .font(.system(size: 16))
                                    .foregroundColor(.black)
                            }
                            .frame(width: 80, height:30)
                        }

                        Button {
                            self.isPublic = true
                        } label: {
                            HStack {
                                Image(systemName: self.isPublic ? "checkmark.circle.fill" : "circle")
                                    .foregroundColor(self.isPublic ? Color.themeColor() : Color.black)
                                Text("公开")
                                    .font(.system(size: 16))
                                    .foregroundColor(.black)
                            }
                            .frame(width: 80, height:30)
                        }
                        
                        Spacer()
                        
                        Button { // 更新经纬度方法
                            
                        } label: {
                            HStack {
                                Image(systemName: "arrow.clockwise")
                                Text("更新经纬度")
                                    .font(.system(size: 16))
                            }
                            .frame(width: 120, height:30)
                            .foregroundColor(Color.themeColor())
                        }
                    }
                    .padding(.vertical, 10)
                    
                    HStack {
                        // 取消按钮
                        Button {
                            self.addAddressAction = false
                        } label: {
                            HStack {
                                Text("取消")
                                    .font(.system(size: 17))
                            }
                            .frame(width: 150, height:44)
                            .foregroundColor(.black)
                            .background(Color(hex: "#F7F7F7"))
                            .cornerRadius(6)
                        }
                        
                        Spacer()
                        // 保存按钮
                        Button {
                            self.showAlert = addressName.isEmpty
                            self.addAddress(text: addressName)
                        } label: {
                            HStack {
                                Text("保存")
                                    .font(.system(size: 17))
                            }
                            .frame(width: 150, height:44)
                            .foregroundColor(.white)
                            .background(Color.themeColor())
                            .cornerRadius(6)
                        }.alert(isPresented: $showAlert, content: {
                            Alert(title: Text("请填写地址名称"))
                        })
                    }
                    .padding(.vertical, 20)
                    
                }.padding(20)
            }
            .background(Color(.white))
            .cornerRadius(8)
        }
    }
    
    //公共cell
    func createPublicCell(address : AddressModel) -> some View{
        HStack{
            Image("地图选点_设置")
            Text(getRecordName(address: address)).font(.system(size: 14))
        }.frame(maxWidth: .infinity, alignment: .leading)
            .padding(.vertical,10)
    }
    func getRecordName(address: AddressModel)->String{
        var name = address.name ?? ""
        if let addr = address.address {
            name = name + "/" + addr
        }
        return name
    }
    
    //私有cell
    func createPrivateCell(address : AddressModel) -> some View{
        HStack{
             Image("地图选点_设置")
            VStack(alignment:.leading){
                HStack{
                    Text("\(address.name!)/\((((address.address) != nil) ? address.address : "")!)").font(.system(size: 14)).frame(maxWidth:.infinity,alignment: .leading)
                    Button {
                        print("地图_编辑 address:\(address.name ?? "")")
                        self.aId = address.id!
                        self.addressName = address.name!
                        self.addAddressAction = true
                    } label: {
                        Image("地图_编辑")
                    }
                    Spacer.width(20)
                    Button {
                        print("地图_删除 address:\(address.name  ?? "")")
                        self.aId = "\(address.id!)"
                        deletAddress()
                    } label: {
                        Image("地图_删除")
                    }
                    
                }
                Text("\(address.longitude!),\(address.latitude!)")
            }
        }.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical,10)
    }
    
}
//
//func saveAddressAction(aId: String, name: String, lat: String, lon: String, type: String, completion: @escaping (Bool) -> Void) {
//    let openId = ViewModel.shared.passenger.openId
//    let laosMobile = ViewModel.shared.passenger.laosMobile
//    let phone = ViewModel.shared.passenger.wechatNo
//    Api.saveAddress(aId: aId, openId: openId, name: name, laosPhone: laosMobile, phone: phone, lat: lat, lon: lon, type: type) { r in
//        completion(true)
//    }
//}


//class MyAddressNetManager: ObservableObject {
//    
//    @Published var addressPublicList: [AddressModel] = []
//    @Published var addressPrivateList: [AddressModel] = []
//    @Published var addressLocalList: [AddressModel] = []
//    
//    func loadLocalAddressList(){
//        // 读取自定义对象列表
//        if let data = UserDefaults.standard.data(forKey: "localAddressList") {
//            do {
//                let decoder = JSONDecoder()
//                let savedAddress = try decoder.decode([AddressModel].self, from: data)
//                print("读取的列表: \(savedAddress)")
//                addressLocalList = savedAddress
//                print("读取的数量:\(addressLocalList.count)")
//            } catch {
//                print("解码失败: \(error)")
//            }
//        }
//    }
//    
//    func clearLocalAddressList(){
//        UserDefaults.standard.set(nil, forKey: "localAddressList")
//        addressLocalList = []
//    }
//    
//    func setLocalAddress(address : AddressModel){
//        
//        var preallocatedArray : [AddressModel] = []
//        if let data = UserDefaults.standard.data(forKey: "localAddressList") {
//            do {
//                let decoder = JSONDecoder()
//                let savedAddress = try decoder.decode([AddressModel].self, from: data)
//                print("读取的列表: \(savedAddress)")
//                preallocatedArray = savedAddress
//            } catch {
//                print("解码失败: \(error)")
//            }
//        }
//        preallocatedArray.append(address)
//        do {
//          
//                
//                
//            let encoder = JSONEncoder()
//            let data = try encoder.encode(preallocatedArray)
//            print("存入的数量:\(preallocatedArray.count)")
//            UserDefaults.standard.set(data, forKey: "localAddressList")
//        } catch {
//            print("编码失败: \(error)")
//        }
//    }
//    
//    
//    
//    func loadAddressList(index: String, keyword: String) {
//        let openId = ViewModel.shared.passenger.openId
//        self.addressPublicList.removeAll()
//        self.addressPrivateList.removeAll()
//        //== 1 ? "private" : "public"
//        Api.getAddressList(openId: openId, type: index , name: keyword) { r in
//            switch r {
//            case .failure(let error):
//                logger.info("error:\(error)")
//            case .success(let addresses):
//                DispatchQueue.main.async {
//                    addresses.forEach { address in
//                        if index == "private" {
//                            self.addressPrivateList.append(address)
//                        }else{
//                            self.addressPublicList.append(address)
//                        }
//                    }
//                }
//            }
//        }
//    }
//    
//}


//struct RadioButton: View {
//    let item: SegmentModel
//    @Binding var selectedOption: SegmentModel
//    let onTap: () -> Void
//    
//    var body: some View {
//        HStack {
//            Image(selectedOption.request == item.request ? "地址_选中" :"地址_未选中").resizable().frame(width:16, height:16)
//            Text(item.title).font(.system(size: 14))
//        }
//        .padding(.vertical, 8)
//        .onTapGesture {
//            selectedOption = item
//            onTap()
//        }
//    }
//}
